<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="1"
      action="#"
      :on-preview="preview"
      :file-list="fileList"
      :class="{disable:disableUpload}"
      class="uploader"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showPercent" style="width: 180px" :percentage="percent" />
    <el-dialog title="图片预览" :visible="showDialog" @close="showDialog = false">
      <img :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 引入腾讯云sdk
const cos = new COS({
  SecretId: 'AKIDUp0wb4O4h3ScPyAp8AukLjqgwwRjQrax', // 身份识别 ID
  SecretKey: 'HvKSDiaDbjKglYJcOxFhuqUevz2susfC' // 身份密钥
})
export default {
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: '',
      currentFileUid: '',
      percent: 0,
      showPercent: false
    }
  },
  computed: {
    disableUpload() {
      return this.fileList.length === 1
    }
  },
  methods: {
    preview(file) {
      console.log(file)
      this.imgUrl = file.url
      this.showDialog = true
    },
    handleRemove(file, fileList) {
      // 第二个参数是删除后的文件列表
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },

    handleChange(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    beforeUpload(file) {
      console.log(file)
      this.currentFileUid = file.uid
      this.showPercent = true
      return true
    },
    upload(params) {
      console.log(params.file)
      if (params.file) {
        cos.putObject({
          Bucket: 'zhanrengu-1303161484', // 存储桶名称
          Region: 'ap-guangzhou', // 存储桶地域
          Key: params.file.name, // 文件名作为key
          StorageClass: 'STANDARD', // 此类写死
          Body: params.file,
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        }, (err, data) => {
          console.log(err, data)
          if (!err && data.statusCode === 200) {
            this.fileList = this.fileList.map(item => {
              console.log(item)
              if (item.uid === this.currentFileUid) {
                return { url: 'http://' + data.Location, upload: true }
              }
              return item
            })
            setTimeout(() => {
              this.showPercent = false
              this.percent = 0
            }, 2000)
          }
        })
      }
    }
  }
}

</script>

<style lang="scss" scoped>
.disable {
  // /deep/ .el-upload--picture-card {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
.uploader {
  ::v-deep img {
    object-fit: cover;
  }
}
</style>
